package Controller.user;

import Controller.BaseHttpServlet;
import Entity.User;
import Services.WebService;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterServlet extends BaseHttpServlet {
	@Override
	protected void processRequest(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action) throws ServletException, IOException {
		if (webServices.getCurrentUser() != null) {
			response.sendRedirect("/member");
		} else if (action != null && action.equals("new")) {
			this.newUser(request, response, webServices, action);
		} else {
			this.forward(request, response, webServices, action, "/auth/register.jsp");
		}
	}

	private void newUser(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action) throws IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String passwordRepeat = request.getParameter("password_repeat");
		String salt = "NO_SALT";
		String email = request.getParameter("email");
		
		String temp = request.getParameter("telephone");
		boolean isTelNotInt = !WebService.isInteger(temp);
		int telephone = (temp == null || isTelNotInt)?-1:Integer.parseInt(temp);
		String role = "ROLE_USER";
		int loyaltyPoint = 0;

		User user = new User();
		user.setEmail(email);
		user.setLoyaltyPoint(loyaltyPoint);
		user.setPassword(password);
		user.setRole(role);
		user.setSalt(salt);
		user.setUsername(username);
		user.setTelephone(telephone);

		boolean isNameUsed = webServices.getEntityManager().checkUsernameIsUsed(username);
		boolean isEmailUsed = webServices.getEntityManager().checkEmailIsUsed(email);
		boolean isPwdNotMatched = !passwordRepeat.equals(password);
		
		if (request.getMethod() == "POST" && !isNameUsed && !isEmailUsed && !isPwdNotMatched && !isTelNotInt && username != null && password != null && email != null && telephone > 0) {
			user = webServices.getEntityManager().newUser(user);
			if (user != null) {
				request.getSession().setAttribute("userID", user.getId());
				webServices.setCurrentUser(user);
				action = "succeeded";
				this.forward(request, response, webServices, action, "/auth/register.jsp");
			}
		} else {
			request.setAttribute("user", user);
			request.setAttribute("isNameUsed", isNameUsed);
			request.setAttribute("isEmailUsed", isEmailUsed);
			request.setAttribute("isPwdNotMatched", isPwdNotMatched);
			request.setAttribute("isTelNotInt", isTelNotInt);
			
			action = "failed";
			this.forward(request, response, webServices, action, "/auth/register.jsp");
		}
	}
}
